<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;

use think\Exception;
use think\Request;
use think\Controller;

/**
 * 地区
 */
class Region extends Controller
{

    protected $model = '';

    public function _initialize()
    {
        $this->model = db('region');
    }

    /**
     * 得到树形地址
     * @return \think\response\Json
     */
    public function getDistrict(){
        $districts = $this->model->where(['level' => 1])->select();
        foreach ($districts as &$item) {
            $city = $this->model->where(['parent_id' => $item['id']])->select();
            $item['child'] = $city;
        }

        $this->assign('districts', $districts);

        return json(['status' => 1, 'data' => $this->fetch('')]);
    }

    /**
     * 获取地区
     */
    public function getRegion(){
        $params = $this->request->param();
        $parentId = $params['p_id'];
        $selected = isset($params['selected']) ? $params['selected'] : 0;
        $level = $params['level'];
        $data = $this->model->where("parent_id = {$parentId} and level = {$level}")->select();
        $html = '';
        if($data){
            foreach($data as $h){
                if($h['id'] == $selected){
                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }

        return json($html);
    }

}